<template>
  <div class="px-[16px] py-[16px] mt-[8px] bg-[var(--base-color)] rounded-[8px]">
    <FormTitle title="财务信息" />
    <div class="flex mb-[8px]">
      <div class="settlement">
        <el-select
          v-model="form.logistics_bp_config_id"
          style="width: 160px"
          filterable
        >
          <el-option
            v-for="item in options['bp_config']"
            :key="item.bp_name"
            :label="item.bp_name"
            :value="item.logistics_bp_config_id"
          />
        </el-select>
      </div>
      <!-- <div class="rounded-[4px] bg-[#fafafa] shadow-[none]">
        <div class="c-input">
          <el-input-number
            v-model="form.pre_pay_scale"
            style="width: 98px"
            :controls="false"
            placeholder="预付比例"
          />%
        </div>
      </div> -->
      <!-- <div class="settlement">
        <el-select v-model="form.settle_type" style="width: 80px" filterable>
          <el-option
            v-for="item in options['settle_type']"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <template v-if="[1, 3].includes(+form.settle_type)">
          <el-input-number
            v-model="form.settle_cycle"
            class="line"
            style="width: 100px"
            placeholder="结算周期"
            :min="1"
            :max="90"
            :controls="false"
          />
          <el-input-number
            v-model="form.settle_pay_day"
            style="width: 120px"
            :min="1"
            :max="31"
            placeholder="付款日"
            :controls="false"
          />
        </template>

        <template v-if="+form.settle_type === 4">
          <el-input-number
            v-model="form.settle_quota"
            class="line"
            style="width: 100px"
            placeholder="额度"
            :controls="false"
          />
          <el-input-number
            v-model="form.settle_day"
            style="width: 120px"
            placeholder="天数"
            :controls="false"
          />
        </template>
      </div> -->
      <div class="c-input">
        <el-select v-model="form.pay_type" style="width: 85px" filterable>
          <el-option
            v-for="item in options['pay_type'] || []"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
    </div>
    <vxe-table
      ref="tableRef"
      :data="data"
      border="full"
      :round="true"
      maxHeight="400"
    >
      <vxe-column
        title="账户类型"
        fixed="left"
        width="160"
        field="account_type"
      >
        <template #header>
          <span class="text-[#f56c6c] mr-[2px]">*</span>
          <span>账户类型</span>
        </template>
        <template #default="{ row }">
          <el-select
            v-model="row.account_type"
            clearable
            filterable
            v-if="notAdd(row)"
          >
            <el-option
              v-for="item in options['account_type'] || []"
              :key="item.label"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </vxe-column>
      <vxe-column fixed="left" title="账户名" width="200" field="account_name">
        <template #header>
          <span class="text-[#f56c6c] mr-[2px]">*</span>
          <span>账户名</span>
        </template>
        <template #default="{ row }">
          <el-input v-model="row.account_name" clearable v-if="notAdd(row)" />
          <el-button v-if="row.type === 'add'" @click="handleAddRow">
            +添加
          </el-button>
        </template>
      </vxe-column>
      <vxe-column title="账号" width="200" field="bank_account">
        <template #header>
          <span class="text-[#f56c6c] mr-[2px]">*</span>
          <span>账号</span>
        </template>
        <template #default="{ row }">
          <el-input v-model="row.bank_account" clearable v-if="notAdd(row)" />
        </template>
      </vxe-column>
      <vxe-column title="币种" width="120" field="currency">
        <template #header>
          <span class="text-[#f56c6c] mr-[2px]">*</span>
          <span>币种</span>
        </template>
        <template #default="{ row }">
          <el-select
            v-model="row.currency"
            clearable
            filterable
            v-if="notAdd(row)"
          >
            <el-option
              v-for="item in dict.currency"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </template>
      </vxe-column>
      <vxe-column title="开户行" width="260" field="bank_name">
        <template #header>
          <span class="text-[#f56c6c] mr-[2px]">*</span>
          <span>开户行</span>
        </template>
        <template #default="{ row }">
          <el-input v-model="row.bank_name" clearable v-if="notAdd(row)" />
        </template>
      </vxe-column>
      <vxe-column title="网点" min-width="260" field="bank_branch">
        <template #header>
          <span class="text-[#f56c6c] mr-[2px]">*</span>
          <span>网点</span>
        </template>
        <template #default="{ row }">
          <el-input v-model="row.bank_branch" clearable v-if="notAdd(row)" />
        </template>
      </vxe-column>
      <vxe-column title="默认收款账号" width="120">
        <template #default="{ row, rowIndex }">
          <el-radio
            :model-value="row.is_default"
            :label="1"
            @change="handleSelectDefault(rowIndex)"
            v-if="notAdd(row)"
          >
            默认
          </el-radio>
        </template>
      </vxe-column>
      <vxe-column title="操作" width="100">
        <template #default="{ row, rowIndex }">
          <el-button
            type="danger"
            link
            v-if="notAdd(row)"
            @click="handleDelete(rowIndex)"
          >
            删除
          </el-button>
        </template>
      </vxe-column>
    </vxe-table>
  </div>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { getCurrency } from "@/api/public";
import FormTitle from "@/components/Form/FormTitle.vue";
const props = defineProps({
  data: { type: Object, default: () => ({}) },
  options: { type: Object, default: () => ({}) },
});
const dict = reactive({
  currency: [],
});
onMounted(() => {
  getStorehouse();
});
const getStorehouse = async () => {
  try {
    const res = await getCurrency();
    dict.currency = res?.data || [];
  } catch (e) {
    console.error(e);
  }
};

const tableData = ref([{ type: "add" }]);

const data = computed(() => tableData.value.filter((n) => n.is_delete !== 1));
const form = ref({
  logistics_bp_config_id: null, // 月结
  pay_type: 2, // 现金
  // settle_quota: undefined,
  // settle_day: "",
  // settle_cycle: undefined,
  // settle_pay_day: undefined,
  // pre_pay_scale: undefined,
});

const emit = defineEmits(["update:modelValue", "refresh"]);

const tableRef = ref();

watch(
  () => props.data,
  (val) => {
    const {
      finance_details = [],
      // settle_quota,
      // settle_day,
      // settle_cycle,
      // settle_pay_day,
      // settle_type = "",
      logistics_bp_config_id = null,
      pay_type = "",
      // pre_pay_scale,
    } = val || {};
    if (!finance_details.length) return;
    tableData.value = finance_details.concat({
      type: "add",
    });
    form.value = {
      // settle_quota,
      // settle_day,
      // settle_cycle,
      // settle_pay_day,
      // settle_type,
      logistics_bp_config_id,
      pay_type,
      // pre_pay_scale,
    };
  }
);

const getTableData = () => {
  return new Promise((resolve, reject) => {
    const {
      // settle_quota,
      // settle_day,
      // settle_cycle,
      // settle_pay_day,
      // settle_type,
      pay_type,
      logistics_bp_config_id,
      // pre_pay_scale,
    } = form.value;
    // const billedMonthly = [1, 3].includes(settle_type);
    // const loan = [4].includes(settle_type);
    // if (billedMonthly) {
    //   if (!settle_cycle || !settle_pay_day) {
    //     ElMessage.warning("请填写财务结算信息");
    //     reject();
    //     return;
    //   }
    // }

    // if (loan) {
    //   if (!settle_quota || !settle_day) {
    //     ElMessage.warning("请填写财务结算信息");
    //     reject();
    //     return;
    //   }
    // }
    let finance_details = tableData.value;
    finance_details = finance_details.filter((n) => n.type !== "add");
    if (!finance_details.length) {
      ElMessage.warning("请至少添加一条财务账户信息");
      reject();
      return;
    }
    const default_finance = finance_details?.find((n) => n.is_default == 1);
    console.log(default_finance);
    if (!default_finance?.account_type) {
      console.log(1);
      ElMessage.warning(`请补充默认财务信息的账户类型信息!`);
      reject();
      return;
    }
    if (!default_finance?.account_name) {
      console.log(2);
      ElMessage.warning(`请补充默认财务信息的账户名信息!`);
      reject();
      return;
    }
    if (!default_finance?.bank_account) {
      console.log(3);
      ElMessage.warning(`请补充默认财务信息的账户信息!`);
      reject();
      return;
    }
    // if (!default_finance?.currency) {
    //   ElMessage.warning(`请补充默认财务信息的币种信息!`)
    //   return
    // }
    if (!default_finance?.bank_name) {
      console.log(4);
      ElMessage.warning(`请补充默认财务信息的开户行信息!`);
      reject();
      return;
    }
    if (!default_finance?.bank_branch) {
      console.log(5);
      ElMessage.warning(`请补充默认财务信息的网点信息!`);
      reject();
      return;
    }

    resolve({
      finance_details,
      // pre_pay_scale,
      // settle_type,
      pay_type,
      logistics_bp_config_id,
      // settle_cycle: billedMonthly ? settle_cycle : undefined,
      // settle_pay_day: billedMonthly ? settle_pay_day : undefined,
      // settle_quota: loan ? settle_quota : undefined,
      // settle_day: loan ? settle_day : undefined,
    });
  });
};

const handleAddRow = async () => {
  tableData.value.splice(
    -1,
    0,
    tableData.value.length > 1
      ? { currency: "CNY" }
      : { is_default: 1, currency: "CNY" }
  );
  await nextTick();
  tableRef.value?.loadData(tableData.value).then(() => {
    const el = tableRef.value.$el.querySelector(".vxe-table--body-wrapper");
    if (el) {
      el.scrollTop = el.scrollHeight;
    }
  });
};

const handleSelectDefault = (index) => {
  tableData.value = tableData.value.map((n, i) => ({
    ...n,
    is_default: i === index ? 1 : 0,
  }));
  nextTick(() => {
    tableRef.value?.loadData(tableData.value);
  });
};

const handleDelete = async (index) => {
  tableData.value[index].is_delete = 1;
  tableData.value.splice(index, 1);
  const hasDefault = tableData.value.some(
    (n) => n.is_default == 1 && n.type !== "add"
  );
  if (!hasDefault) {
    tableData.value[0].is_default = 1;
  }
  await nextTick();
  tableRef.value?.loadData(tableData.value);
};

const notAdd = (row) => row.type !== "add";

defineExpose({ getTableData });
</script>
<style lang="scss" scoped>
.c-input {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #333;
  background-color: var(--base-small-bg-color);
  padding: 0 8px;
  :deep(.el-input__wrapper) {
    box-shadow: none;
    background-color: var(--base-small-bg-color);
  }
}

.settlement {
  display: flex;
  align-items: center;
  background-color: var(--base-small-bg-color);
  margin-right: 16px;
  :deep(.el-input__wrapper) {
    background-color: var(--base-small-bg-color);
    box-shadow: none;
    &:hover {
      box-shadow: none;
    }
  }
  :deep(.el-select .el-input.is-focus .el-input__wrapper) {
    box-shadow: none !important;
  }
  .line {
    border-left: 1px solid #e6e7e9;
    border-right: 1px solid #e6e7e9;
  }
}
</style>
